#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <pthread.h>

#define NUM 100
long long num = 0;
pthread_mutex_t mutex; // 互斥信号量

void *thread_inc(void *arg){
    for (size_t i = 0; i < 5000000; i++){
        // 加锁
        pthread_mutex_lock(&mutex);
        ++num;
        // 释放锁
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}
void *thread_des(void *arg){
    for (size_t i = 0; i < 5000000; i++){
        // 加锁
        pthread_mutex_lock(&mutex);
        --num;
        // 释放锁
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}

int main(){

    // long long 大小
    printf("sizeof long long is %ld\n",sizeof(long long));
    pthread_t tids[NUM];
    // 初始化互斥信号量
    pthread_mutex_init(&mutex, NULL);

    // 创建线程
    for (size_t i = 0; i < NUM; i++){
        if (i % 2 == 0){
            pthread_create(&tids[i], NULL, thread_inc, NULL);
        }else{
            pthread_create(&tids[i], NULL, thread_des, NULL);
        }
    }
    
    for (size_t i = 0; i < NUM; i++){
        pthread_join(tids[i], NULL);
    }

    printf("num is [%lld]\n",num);

    // 销毁互斥信号量
    pthread_mutex_destroy(&mutex);

    return 0;
}